package cn.itcast.algorithm.search;

/**
 * 二分查找
 * create by zhangtian3 on 2019/3/25
 */
public class BiarySearch {
    public static int bsearch(int[] a, int n, int value) {
        int low = 0 ;
        int high = n - 1 ;
        while(low <= high){
            // int mid = (low + high) / 2 ;
            int mid = high - (high - low) /2 ; // 避免二分找找引起的数值越界问题

            if(a[mid] == value){
                return mid ;
            }else if(a[mid] < value){
                low = mid + 1 ;
            }else {
                high = mid - 1 ;
            }
        }

        return -1 ;
    }

    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6} ;
        int value = 6 ;
        System.out.println(bsearch(arr, arr.length, value));
    }
}
